<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=0.7, minimum-scale=0.2, maximum-scale=1.0, user-scalable=yes"/>
    <title>导航</title>
    <script src="common.js"></script>
    <link href="boot.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }

        .container {
            text-align: center;
        }

        h2 {
            margin-bottom: 30px;
        }

        button {
            padding: 10px 20px;
            margin: 0 10px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }

        .popup-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .popup-container h2 {
            margin-bottom: 15px;
        }

        .popup-container input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        .popup-container button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .popup-container button:hover {
            background-color: #0056b3;
        }

        .popup-container_waiting_join {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 50px; /* 增加 padding 大小 */
            padding-right: 50px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

        .popup-container_select_role {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 50px; /* 增加 padding 大小 */
            padding-right: 50px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

        .popup-container_waiting_select {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 50px; /* 增加 padding 大小 */
            padding-right: 50px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

    </style>
</head>
<body>
<div class="container">
    <h2>请选择您要进行的操作：</h2>
    <button id="joinButton" onclick="joinRoom()">开始BP</button>
    <button id="backButton" onclick="backToRoom()">重回房间</button>
    <button onclick="viewBPRecords()">查看BP记录</button>
    <button onclick="logout()">退出账号</button>
</div>

<div class="popup-container_waiting_join" id="popup_waiting_join" style="display: none;">
    <p>等待其他玩家加入...</p>
</div>

<div class="popup-container_select_role" id="popup_select_role" style="display: none;">
    <p>抽签胜利，请决定本方战队本轮比赛的bp先后顺序</p>
    <button onclick="selectA()">先手</button>
    <button onclick="selectB()">后手</button>
</div>

<div class="popup-container_waiting_select" id="popup_waiting_select" style="display: none;">
    <p>抽签失败，请等待对方战队决定本轮比赛的bp先后顺序</p>
</div>

<script>
    if (sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "undefined") {
        window.location.href = '/bp/login.html'; // 替换为你想要跳转的页面的URL
    }

    function getRunningRoom() {
        getRunningRoomId(function () {
            var joinButton = document.getElementById('joinButton');
            var backButton = document.getElementById('backButton');
            if (localStorage.getItem('runningRoomId') == null) {
                joinButton.style.display = 'inline';
                backButton.style.display = 'none';
            } else {
                joinButton.style.display = 'none';
                backButton.style.display = 'inline';
                localStorage.setItem('roomId', localStorage.getItem('runningRoomId'));
                handleInto();
            }
        });
    }

    var socket = null; // 声明 socket 变量，用于存储 WebSocket 对象
    var socketUrl = "ws://" + ip + ":8081/ws"; // 替换为实际的 WebSocket 服务器地址
    var reconnectTimer = null; // 重新连接的定时器
    var block = null;
    var startGetRunningRoom = false;
    // 在页面加载时执行此函数

    connect();

    function connect() {
        if (sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "undefined") {
            window.location.href = '/bp/login.html'; // 替换为你想要跳转的页面的URL
        }
        // 创建 WebSocket 连接
        socket = new WebSocket(socketUrl);
        // 连接成功时的回调函数
        socket.onopen = function (event) {
            cancelReconnect();
            login();
            // console.log("WebSocket 连接已建立.");
            // 连接成功后取消重新连接的定时器
        };

        // 收到消息时的回调函数
        socket.onmessage = function (event) {
            handle(event);
        };

        // 监听连接关闭事件
        socket.onclose = function (event) {
            // 如果连接仍然关闭，启动重新连接的定时器
            startReconnect();
        };
    }

    // 开始重新连接的定时器
    function startReconnect() {
        if (!reconnectTimer) {
            reconnectTimer = setInterval(connect, 3000); // 每秒尝试重新连接
        }
    }

    // 取消重新连接的定时器
    function cancelReconnect() {
        if (reconnectTimer) {
            clearInterval(reconnectTimer);
            reconnectTimer = null;
        }
    }

    function handle(event) {
        var message = JSON.parse(event.data); // 将收到的消息解析为 JSON 对象
        var action = message.action; // 获取消息中的 action 属性
        // 根据 action 属性分发处理逻辑
        switch (action) {
            case "LOGIN":
                getRunningRoom();
                break;
            case "CREATE_ROOM":
                localStorage.setItem('roomId', message.roomId);
                handleCreateRoom();
                break;
            case "JOIN_ROOM":
                localStorage.setItem('roomId', message.roomId);
                handleJoinRoom(message.content);
                break;
            case "INTO":
                handleInto();
                break;
            case "JOIN_ROOM_ERROR":
                showAlert('暂未安排赛程', 'alert-danger');
                break;
            case "JOIN_ROOM_ERROR_RUNNING":
                showAlert('还有正在进行中的赛程', 'alert-danger');
                break;
            case "NOT_START":
                showAlert('等待BP开始', 'alert-danger');
                break;
            case "KICK":
                showAlert('账号在其他地方被登录', 'alert-danger');
                socket.close()
                cancelReconnect();
                setInterval(logout, 3000);
                break;
            default:
                //如果有其他的消息，可能是进入房间了
                // getRunningRoom();
                // console.log("Unknown action:", action);
                if (!startGetRunningRoom) {
                    setInterval(getRunningRoom, 3000);
                    startGetRunningRoom = true;
                }
                break;
        }
    }

    // 发送消息的函数
    function sendMessage(message) {
        socket.send(message);
    }

    function login() {
        // 创建房间的逻辑
        var loginRequest = {
            action: "LOGIN",
            content: sessionStorage.getItem('username'),
            otherMessage: "导航页面登陆"
        };
        var jsonString = JSON.stringify(loginRequest);
        sendMessage(jsonString);
    }

    function joinRoom() {
        var joinRoomRequest = {
            action: "JOIN_ROOM",
        };
        var jsonString = JSON.stringify(joinRoomRequest);
        sendMessage(jsonString);
    }

    function selectA() {
        // 创建房间的逻辑
        var request = {
            action: "SELECT_ROLE",
            roomId: localStorage.getItem('roomId'),
            content: "A"
        };
        var jsonString = JSON.stringify(request);
        sendMessage(jsonString);
    }

    function selectB() {
        // 创建房间的逻辑
        var request = {
            action: "SELECT_ROLE",
            roomId: localStorage.getItem('roomId'),
            content: "B"
        };
        var jsonString = JSON.stringify(request);
        sendMessage(jsonString);
    }

    function viewBPRecords() {
        // 点击“查看BP记录”按钮后的操作，例如跳转到BP记录页面
        window.location.href = '/bp/record.html'; // 替换为你想要跳转的页面的URL
    }

    function logout() {
        // 点击“退出账号”按钮后的操作，例如跳转到退出登录页面
        sessionStorage.removeItem("username")
        window.location.href = '/bp/login.html'; // 替换为实际的退出登录页面URL
    }

    // 处理不同 action 的方法示例
    function handleCreateRoom() {
        block = document.getElementById('popup_waiting_join')
        block.style.display = 'block';
    }

    function handleJoinRoom(content) {
        // console.log("处理加入房间的逻辑:", content);
        // 解析数据结构
        var data = JSON.parse(content);

        var users = data.users;

        // 获取当前用户的角色
        var currentUserRole = getCurrentUserRole(users);

        // 弹出相应的弹窗
        if (currentUserRole === 'F') {
            if (block != null) {
                block.style.display = 'none';
            }
            block = document.getElementById('popup_select_role')
            block.style.display = 'block';
        } else if (currentUserRole === 'S') {
            if (block != null) {
                block.style.display = 'none';
            }
            block = document.getElementById('popup_waiting_select')
            block.style.display = 'block';
        }

        // 获取当前用户的角色
        function getCurrentUserRole(users) {
            // 这里可以根据具体逻辑来确定当前用户的角色，比如根据用户名查找用户信息等
            // 这里简单地返回第一个用户的角色作为当前用户的角色
            return users[0].username === sessionStorage.getItem("username") ? users[0].role : users[1].role;
        }
    }

    function getRunningRoomId(callback) {
        const formData = new FormData();
        formData.append('username', sessionStorage.getItem("username"));
        // 发送POST请求
        fetch('http://' + ip + ':8080/getRunningRoom', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.result === "ok") {
                    localStorage.setItem('runningRoomId', data.schedule.roomId);
                } else {
                    localStorage.removeItem('runningRoomId');
                }
                callback()
            });
    }

    function backToRoom() {
        if (localStorage.getItem('roomId') == null) {
            getRoomId(handleInto);
        } else {
            handleInto();
        }
    }

    function handleInto() {
        if (localStorage.getItem('roomId') == null) {
            showAlert('没有可进入的房间', 'alert-danger');
        } else {
            if (block != null) {
                block.style.display = 'none';
            }
            window.location.href = '/bp/home.html'; // 替换为你想要跳转的页面的URL
        }
    }

    function showAlert(message, className) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert ${className} mt-4`;
        alertDiv.textContent = message;
        // 居中显示
        alertDiv.style.position = 'fixed';
        alertDiv.style.top = '50%';
        alertDiv.style.left = '50%';
        alertDiv.style.transform = 'translate(-50%, -50%)';

        document.body.appendChild(alertDiv);


        // 3秒后自动关闭弹窗
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
</script>
</body>
</html>
